package gazzera.node.core;

import gazzera.gui.*;
import gazzera.node.core.messages.*;
import gazzera.node.core.peer.*;

import java.util.*;


public class PluginManager
{
	private List<Plugin> plugins = new ArrayList<Plugin>();
	private ICore ctx = null;
	
	public PluginManager()
	{
	    
	}
	
	@SuppressWarnings("unchecked")
	public <T extends Plugin> T getPlugin(Class<T> cls)
	{
		for (Plugin p : plugins)
		{
			if (p.getClass().equals(cls))
			{
				return (T)p;
			}
		}
		return null;
	}
	
	public void install(Plugin p)
	{
	    plugins.add(p);
	}
	public void message(Node node, Message msg)
	{
	    for (Plugin p : plugins)
	    {
	    	try
			{
				p.message(node, msg);
			}
			catch (Exception e)
			{
				ctx.logErr(e);
			}
	    }
	}
	public void init(ICore ctx)
	{
	    this.ctx = ctx;
	    
	    for (Plugin p : plugins)
	    {
	    	try
			{
	    		System.out.println("Initializing "+p.getClass().getName());
				p.init(ctx);
			}
			catch (Exception e)
			{
				ctx.logErr(e);
			}
	    }
	}
	public void start()
	{   
	    for (Plugin p : plugins)
	    {
	    	try
			{
				p.start();
			}
			catch (Exception e)
			{
				ctx.logErr(e);
			}
	    }
	}
	public void finish()
	{
	    for (Plugin p : plugins)
	    {
	    	try
			{
				p.finish();
			}
			catch (Exception e)
			{
				ctx.logErr(e);
			}
	    }
	}
	public void command(GuiMessage msg)
	{
		   for (Plugin p : plugins)
		    {
		    	try
				{
					p.command(msg);
				}
				catch (Exception e)
				{
					ctx.logErr(e);
				}
		    }
	}
	public void taskTerminated(Task task, boolean interrupted)
	{
		for (Plugin p : plugins)
	    {
	    	try
			{
				p.taskTerminated(task, interrupted);
			}
			catch (Exception e)
			{
				ctx.logErr(e);
			}
	    }
	}
	public void dataPumpTerminated(Node node, DataPumpSource src)
	{
	    for (Plugin p : plugins)
	    {
	    	try
			{
				p.dataPumpTerminated(node, src);
			}
			catch (Exception e)
			{
				ctx.logErr(e);
			}
	    }
	}
	public void nodeConnected(Node node)
	{
	    for (Plugin p : plugins)
	    {
	    	try
			{
				p.nodeConnected(node);
			}
			catch (Exception e)
			{
				ctx.logErr(e);
			}
	    }

	}
	public void nodeDisconnected(Node node)
	{
	    for (Plugin p : plugins)
	    {
	    	try
			{
				p.nodeDisconnected(node);
			}
			catch (Exception e)
			{
				ctx.logErr(e);
			}
	    }

	}

}
